package org.simplecrm.domain.user;

import org.simplecrm.domain.usergroup.UserGroup;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 * Created by oler on 09.09.14.
 */
@Entity
@NamedQueries({
        @NamedQuery(name = "User.userByName", query = "SELECT u FROM User u WHERE u.login= :username"),
        @NamedQuery(name = "User.userByGroup", query = "SELECT u FROM User u WHERE u.userGroup.id = :usergroupId")
})
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;

    @Column(name = "login")
    @NotNull
    @Size(min = 2, max = 30)
    private String login;

    @Column(name = "password")
    @NotNull
    @Size(min = 2, max = 30)
    private String password;

    @ManyToOne(cascade = {CascadeType.REFRESH})
    @JoinColumn(name = "usergroupId", referencedColumnName = "id", nullable = false)
    private UserGroup userGroup;

    public User() {
    }

    public User(String login, String password, UserGroup userGroup) {
        this.login = login;
        this.password = password;
        this.userGroup = userGroup;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public UserGroup getUserGroup() {
        return userGroup;
    }

    public void setUserGroup(UserGroup userGroup) {
        this.userGroup = userGroup;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        if (id != null ? !id.equals(user.id) : user.id != null) return false;
        if (login != null ? !login.equals(user.login) : user.login != null) return false;
        if (password != null ? !password.equals(user.password) : user.password != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id != null ? id.hashCode() : 0;
        result = 31 * result + (login != null ? login.hashCode() : 0);
        result = 31 * result + (password != null ? password.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", login='" + login + '\'' +
                ", password='" + password + '\'' +
                ", userGroup=" + userGroup +
                '}';
    }
}
